package com.nut.web;

import com.google.gson.Gson;
import com.nut.common.Result;
import com.nut.pojo.User;
import com.nut.service.UserService;
import com.nut.service.impl.UserServiceImpl;
import com.nut.utils.JsonUtils;
import com.nut.utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

public class UserServlet extends BaseServlet {

    private final UserService userService = new UserServiceImpl();

    /**
     * 处理登录的功能
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //  1、获取请求的参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        // 调用 userService.login()登录处理业务
        User loginUser = userService.login(new User(null, username, password, null));
        // 如果等于null,说明登录 失败!
        if (loginUser == null) {
            resp.getWriter().write(JsonUtils.toJson(Result.error().data("msg", "用户或密码错误！").data("username", username)));
        } else {
            req.getSession().setAttribute("user", loginUser);
            resp.getWriter().write(JsonUtils.toJson(Result.ok().data("user", loginUser)));
        }

    }

    /**
     * 处理注销的功能
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.销毁session中用户信息或者销毁session
        req.getSession().invalidate();
        //2.重定向到首页(pages/client/index.jsp)
        resp.sendRedirect(req.getContextPath());
    }

    /**
     * 处理注册的功能
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void regist(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取session中的验证码
        String token = (String) req.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        //删除session中的验证码
        req.getSession().removeAttribute(KAPTCHA_SESSION_KEY);
        //  1、获取请求的参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        String code = req.getParameter("code");
        System.out.println("username=" + username);

        User user = WebUtils.copyParamToBean(req.getParameterMap(), new User());

        //2、检查 验证码是否正确
        if (token != null && token.equalsIgnoreCase(code)) {
        //3、检查 用户名是否可用
            if (userService.existsUsername(username)) {
                resp.getWriter().write(JsonUtils.toJson(Result.error().data("msg", "用户名已存在！！").data("username", username).data("email", email)));

            } else {
                userService.registUser(new User(null, username, password, email));
                Integer id = userService.getUserMaxId();
                user.setId(id);
                resp.getWriter().write(JsonUtils.toJson(Result.ok().data("user", user)));
            }
        } else {
            resp.getWriter().write(JsonUtils.toJson(Result.error().data("msg", "验证码错误！！").data("username", username).data("email", email)));
        }

    }

    /**
     * 处理ajax请求
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void ajaxExistsUsername(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求参数
        String username = req.getParameter("username");
        //调用userService.existsUsername方法
        boolean existsUsername = userService.existsUsername(username);
        //把返回结果封装成map对象
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("existsUsername", existsUsername);
        Gson gson = new Gson();
        String json = gson.toJson(resultMap);
        resp.getWriter().write(json);
    }
}
